package com.teach;

import java.util.HashMap;
import java.util.Map;

/**
 * <pre>
 * TODO : 通用结果Result,建议Restful返回结果尽量使用该类
 *  -用于SpringMVC的JSON消息返回
 *  -消息属性：
 * 		- ok:true/false
 * 		- code:int 消息编号
 * 		- data:Object 数据
 *  	- message:String 消息内容
 * ClassName : com.teach.R
 * Author : J.L.Zhou
 * Tel : 15111047708
 * E-Mail : 12020042@qq.com
 * Date : 2020-05-02 11:57
 * Version : 1.0
 * </pre>
 */
public class R extends HashMap<String, Object> {

	private static final long serialVersionUID = 1L;

	private Boolean ok;
	private String message;
	private Integer code;
	private Object data;

	public R() {
		this(true);
	}

	public R(boolean ok) {
		super();
		this.ok = ok;
		put("ok",ok);
	}

	public static R error() {
		return new R(false);
	}

	public static R error(int code) {
		return new R(false);
	}

	public static R error(String message) {
		return new R(false).setMessage(message);
	}

	public static R error(int code, String message) {
		return new R(false).setCode(code).setMessage(message);
	}

	public static R error(Map<String, Object> map) {
		R r = new R(false);
		r.putAll(map);
		return r;
	}

	public static R empty() {
		return new R();
	}

	public static R ok() {
		return new R(true);
	}

	public static R ok(int code) {
		return new R(true).setCode(code);
	}

	public static R ok(String message) {
		return new R(true).setMessage(message);
	}

	public static R ok(int code, String message) {
		return new R(true).setCode(code).setMessage(message);
	}

	@Override
	public R put(String key, Object value) {
		switch (key) {
		case "data":
			this.data = value;
			break;
		case "message":
			this.message = value.toString();
			break;
		case "ok":
			this.ok = (Boolean) value;
			break;
		case "code":
			this.code = (Integer) code;
			break;
		}
		super.put(key, value);
		return this;
	}

	@Override
	public R remove(Object key) {
		super.remove(key);
		return this;
	}

	public Boolean getOk() {
		return ok;
	}

	public R setOk(Boolean ok) {
		return put("ok",ok);
	}

	public String getMessage() {
		return message;
	}

	public R setMessage(String message) {
		return put("message",message);
	}

	public Integer getCode() {
		return code;
	}

	public R setCode(Integer code) {
		return put("code",code);
	}

	public Object getData() {
		return data;
	}

	public R setData(Object data) {
		return put("data",data);
	}

}

